package cc.yiueil.controller;

import cc.yiueil.model.dto.UserLoginDTO;
import cc.yiueil.model.vo.ResultVO;
import cc.yiueil.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

@RestController
public class LoggedController {

    private static final Logger log = LoggerFactory.getLogger(LoggedController.class);

    @Autowired
    UserService userService;

    @PostMapping(value = "/customLogin")
    public ResultVO<String> customLogin(@RequestBody UserLoginDTO userLoginDTO) {
        try {
            String id_token = userService.authorize(userLoginDTO);
            return ResultVO.authSuccess(id_token);
        } catch (Exception e) {
            log.debug("msg: {}", e.getMessage());
            return ResultVO.authFail(e.getMessage());
        }
    }

    @PostMapping(value = "/customLogout")
    public ResultVO<String> customLogout() {
        try {
            userService.logout();
            return ResultVO.success("登出成功");
        } catch (Exception e) {
            return ResultVO.fail(e.getLocalizedMessage());
        }
    }

    @GetMapping(value = "/hello")
    public ResultVO<String> hello(){
        return ResultVO.success(String.format("Hello %s!", SecurityContextHolder.getContext().getAuthentication().getName()));
    }

    @PreAuthorize(value = "hasAnyRole('ADMIN')")
    @PutMapping(value = "/insert")
    public ResultVO<String> insert() {
        return ResultVO.success("insert success");
    }

    @PreAuthorize(value = "hasAnyRole('ADMIN')")
    @PostMapping(value = "/update")
    public ResultVO<String> update() {
        return ResultVO.success("update success");
    }

    @PreAuthorize(value = "hasAnyRole('ADMIN')")
    @PostMapping(value = "/delete")
    public ResultVO<String> delete() {
        return ResultVO.success("delete success");
    }

    @PreAuthorize(value = "hasAnyRole('USER', 'ADMIN')")
    @PostMapping(value = "/get")
    public ResultVO<String> get() {
        return ResultVO.success("get success");
    }
}
